/**
 * 
 */
package com.jinmei.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.web.context.ServletContextAware;

/**
 * @author richard
 *
 */
public class ResourceManager implements ServletContextAware {
	
	public static final String RESOURCE_NAME = "/WEB-INF/config/resources.properties";
	public static final String DEBUG_RESOURCE_NAME = "C:\\mockD\\JINMEI\\workspace\\JINMEI\\test.properties";
	private static final Logger logger = Logger.getLogger(ResourceManager.class);
	private static final boolean isDebug = false;
	
	private static Properties props = new Properties();
	private static ServletContext servletContext;
	
	static void loadProperties() throws IOException {
		InputStream input = null;
		input = new BufferedInputStream(
				new FileInputStream(getResourceFileName()));
		logger.info("load resource file: " + getResourceFileName());
		props.load(input);
	}
	
	public static String getValue(String key) {
		if (props == null) return null;
		return props.getProperty(key);
	}
	
	public static void setValue(String key, String value) throws IOException {
		if (props == null) {
			props = new Properties();
		}
		
		props.setProperty(key, value);
		OutputStream output = new FileOutputStream(getResourceFileName());
		props.store(output, null);
	}

	private static String getResourceFileName() {
		return isDebug ? DEBUG_RESOURCE_NAME : servletContext.getRealPath("/") + RESOURCE_NAME;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		ResourceManager.servletContext = servletContext;
	}
	
}
